from flask import Flask, request, render_template, Response, redirect, jsonify
from werkzeug.utils import secure_filename
import os
import threading
import time
import queue
import requests
import business
from flask import Flask, request, render_template, Response, redirect, jsonify
import json
import os

CONFIG_PATH = 'config.json'

def load_config():
    try:
        with open(CONFIG_PATH, 'r') as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        # 创建默认配置
        default_config = {
            "zentao_url": "http://127.0.0.1:80/zentao/api.php/v1",
            "xmind2testcase_url": "http://127.0.0.1:5001/",
            "zen_tao_importer_url": "http://127.0.0.1:5002/import"
        }
        with open(CONFIG_PATH, 'w') as f:
            json.dump(default_config, f, indent=4)
        return default_config

def save_config(new_config):
    with open(CONFIG_PATH, 'w') as f:
        json.dump(new_config, f, indent=4)

app = Flask(__name__)
app.secret_key = 'your_secret_key'

UPLOAD_FOLDER = os.path.join(os.getcwd(), "uploads")
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 用于标记后台任务是否完成
job_done = False

@app.route("/start", methods=["POST"])
def start_job():
    global job_done
    job_done = False
    account = request.form.get("account")
    password = request.form.get("password")
    product_id = request.form.get("product_id")
    csv_file = request.files.get("csv_file")
    ZENTAO_URL = request.form.get("zentao_url")

    if not ZENTAO_URL or not account or not password or not product_id or not csv_file:
        return "请填写所有字段并上传CSV文件！"

    filename = secure_filename(csv_file.filename)
    tmp_csv_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    csv_file.save(tmp_csv_path)
    business.logger.info(f"CSV文件已保存到: {tmp_csv_path}")

    def job():
        business.background_job(ZENTAO_URL, account, password, product_id, tmp_csv_path)
        global job_done
        job_done = True

    thread = threading.Thread(target=job)
    thread.start()

    return render_template("log.html")

@app.route("/stream")
def stream():
    def generate():
        while not job_done or not business.log_queue.empty():
            try:
                msg = business.log_queue.get(timeout=1)
                yield f"data: {msg}\n\n"
            except queue.Empty:
                time.sleep(0.5)
                continue
    return Response(generate(), mimetype="text/event-stream")

@app.route("/query-products", methods=["POST"])
def query_products():
    data = request.json
    ZENTAO_URL = data.get("zentao_url")
    account = data.get("account")
    password = data.get("password")

    if not ZENTAO_URL or not account or not password:
        return jsonify({"error": "缺少必要参数"}), 400

    token = business.get_token(ZENTAO_URL, account, password)
    if not token:
        return jsonify({"error": "认证失败，请检查账号密码"}), 401

    try:
        response = requests.get(
            f"{ZENTAO_URL}/products",
            headers={"Token": token},
            timeout=10
        )
        response.raise_for_status()
        products_data = response.json()
        products = [
            {"name": p["name"], "id": p["id"]}
            for p in products_data.get("products", [])
        ]
        return jsonify({"products": products})
    except Exception as e:
        return jsonify({"error": f"接口请求失败: {str(e)}"}), 500


@app.route("/product-query", methods=["GET"])
def product_query_page():
    config = load_config()
    return render_template("product_query.html",
                          default_zentao_url=config['zentao_url'])

@app.route("/import", methods=["GET"])
def index():
    config = load_config()
    return render_template("import.html",
                         zentao_url=config['zentao_url'],
                         xmind_url=config['xmind2testcase_url'])

@app.route("/", methods=["GET"])
def home():
    return redirect("/import")

# 添加配置API
@app.route('/get-config')
def get_config():
    return jsonify(load_config())

@app.route('/save-config', methods=['POST'])
def save_config_route():
    try:
        new_config = request.json
        save_config(new_config)
        return jsonify({"status": "success"})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5002, debug=False)
